#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
K713调试脚本 - 检查数据解析问题
"""

import re
from enhanced_ploop_processor import EnhancedPLoopProcessor

def debug_k713():
    print("=== K713调试脚本 ===")
    
    filename = "test-data/1KA-ARCH-P-R-K713.txt"
    
    # 读取文件内容
    with open(filename, 'r', encoding='utf-8') as f:
        content = f.read()
    
    print(f"文件内容长度: {len(content)} 字符")
    print(f"前200字符:\n{content[:200]}")
    
    # 查找框架名称
    framework_pattern = r'NEW FRMWORK\s+(.+)'
    framework_matches = re.findall(framework_pattern, content)
    print(f"\n框架匹配: {framework_matches}")
    
    # 查找PLOOP
    ploop_pattern = r'NEW PLOOP'
    ploop_matches = re.findall(ploop_pattern, content)
    print(f"PLOOP匹配: {len(ploop_matches)} 个")
    
    # 查找PAVERT
    pavert_pattern = r'NEW PAVERT'
    pavert_matches = re.findall(pavert_pattern, content)
    print(f"PAVERT匹配: {len(pavert_matches)} 个")
    
    # 查找位置坐标
    pos_pattern = r'POS\s+(.+)'
    pos_matches = re.findall(pos_pattern, content)
    print(f"位置匹配: {len(pos_matches)} 个")
    for i, pos in enumerate(pos_matches[:5]):  # 只显示前5个
        print(f"  {i}: {pos}")
    
    # 查找高度
    height_pattern = r'HEIG\s+(\d+\.?\d*)mm'
    height_matches = re.findall(height_pattern, content)
    print(f"高度匹配: {height_matches}")
    
    # 尝试用处理器解析
    print(f"\n=== 尝试用处理器解析 ===")
    processor = EnhancedPLoopProcessor()
    
    try:
        ploop_data = processor.parse_file(filename)
        print(f"解析成功: {len(ploop_data) if ploop_data else 0} 个PLOOP")
        if ploop_data:
            for i, ploop in enumerate(ploop_data):
                print(f"PLOOP {i}: {ploop}")
    except Exception as e:
        print(f"解析失败: {e}")
        import traceback
        traceback.print_exc()

def manual_parse_k713():
    """手动解析K713数据"""
    print(f"\n=== 手动解析K713 ===")
    
    filename = "test-data/1KA-ARCH-P-R-K713.txt"
    
    with open(filename, 'r', encoding='utf-8') as f:
        lines = f.readlines()
    
    vertices = []
    current_pos = None
    framework_name = None
    height = None
    
    for line in lines:
        line = line.strip()
        
        if line.startswith('NEW FRMWORK'):
            framework_name = line.split()[2]
        
        elif line.startswith('HEIG'):
            height_match = re.search(r'(\d+\.?\d*)mm', line)
            if height_match:
                height = float(height_match.group(1))
        
        elif line.startswith('POS'):
            # 解析位置 POS W 9100mm N 4600mm U 0mm
            pos_parts = line.split()
            x, y, z = 0, 0, 0
            
            for i in range(1, len(pos_parts), 2):
                if i + 1 < len(pos_parts):
                    direction = pos_parts[i]
                    value_str = pos_parts[i + 1]
                    value = float(re.search(r'(-?\d+\.?\d*)', value_str).group(1))
                    
                    if direction == 'W':
                        x = -value  # W是西，负方向
                    elif direction == 'E':
                        x = value   # E是东，正方向
                    elif direction == 'N':
                        y = value   # N是北，正方向
                    elif direction == 'S':
                        y = -value  # S是南，负方向
                    elif direction == 'U':
                        z = value   # U是上，正方向
            
            current_pos = (x, y, z)
            print(f"解析位置: {line} → ({x}, {y}, {z})")
        
        elif line.startswith('NEW PAVERT') and current_pos:
            vertices.append(current_pos)
            current_pos = None
    
    print(f"\n解析结果:")
    print(f"框架名称: {framework_name}")
    print(f"高度: {height}mm")
    print(f"顶点数: {len(vertices)}")
    
    for i, vertex in enumerate(vertices):
        print(f"顶点 {i}: {vertex}")
    
    return {
        'framework_name': framework_name,
        'height': height,
        'vertices': vertices
    }

if __name__ == "__main__":
    debug_k713()
    manual_parse_k713() 